/*
 * @FileName: OrganizationService.java
 * 
 * @Author
 * 
 * @Description:
 * 
 * @Date 2016年1月7日 下午2:42:39
 * 
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import java.util.Date;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.SysUser;
import cn.hpclub.server.util.Base64Utils;
import cn.hpclub.server.util.DESAS;
import cn.hpclub.server.util.DESCrypto;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.RSAUtils;

/**
 * Class description goes here
 *
 * @author
 */
public class AccountService{
    private static final Logger  logger      = LoggerFactory.getLogger(AccountService.class);
    public static AccountService service     = new AccountService();
    private static final Pattern PSW_PATTERN = Pattern.compile("^[\\@A-Za-z0-9\\!\\#\\$\\%\\^\\&\\*\\.\\~]{8,20}$");
    private DESAS                desas;

    private AccountService(){
        try{
            desas = new DESAS();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 修改密码，如果因为参数问题修改失败的话，抛出异常
     * 
     * @param 加密后的id
     * @param password
     * @param newPassword
     * @param privateKey
     */
    public void updatePassword(String id, String password, String newPassword, String privateKey){
        try{
            id= decryptId(id);
        }
        catch(Exception e1){
            e1.printStackTrace();
            throw new RuntimeException("密码修改失败，id解密错误");
        } 
        SysUser sysUser = SysUser.dao.findById(id);
        if(null == sysUser){
            throw new RuntimeException("密码修改失败，不存在 id = " + id + " 这个人");
        }
        String salt = sysUser.getStr(SysUser.SALT);

        String desOldPwd = "";
        String desNewPwd = "";
        try{
            /* RSA 解密 */
            String oldPwdByRSA = new String(RSAUtils.decryptByPrivateKey(Base64Utils.decode(password), privateKey));
            desOldPwd = DESCrypto.encryptPassword(oldPwdByRSA, salt);

            String newPwdByRSA = new String(RSAUtils.decryptByPrivateKey(Base64Utils.decode(newPassword), privateKey));
            if(!PSW_PATTERN.matcher(newPwdByRSA).matches()){// 密码不满足正则表达式
                throw new RuntimeException("密码修改失败，密码不满足规则（8-20位非中文字符）");
            }
            desNewPwd = DESCrypto.encryptPassword(newPwdByRSA, salt);
        }
        catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException("密码修改失败，密码解密异常");
        }

        String correct = sysUser.getStr(SysUser.PASSWORD);

        if(!desOldPwd.equals(correct)){
            throw new RuntimeException("密码修改失败，原密码错误");
        }
        sysUser.set(SysUser.PASSWORD, desNewPwd).set(SysUser.LAST_UPDATEED_BY, InterfaceUtil.getAdminId())
                .set(SysUser.LAST_UPDATEED_TIME, new Date());
        sysUser.update();
    }

    public boolean resetPassword(String id){
        try{
            String decryptId = decryptId(id);
            SysUser sysUser = SysUser.dao.findUserById(decryptId);
            if(null == sysUser){
                return false;
            }
            String salt = sysUser.getStr(SysUser.SALT);
            String desNewPwd = "";
            desNewPwd = DESCrypto.encryptPassword("pt5b@#B5TP", salt);
            sysUser.set(SysUser.PASSWORD, desNewPwd).set(SysUser.LAST_UPDATEED_BY, InterfaceUtil.getAdminId())
                    .set(SysUser.LAST_UPDATEED_TIME, new Date());
            sysUser.update();
            return true;
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return false;
    }

    public Object[] delete(String[] ids){
        Object[] result = new Object[2];
        if(ids == null || ids.length == 0){
            result[0] = false;
            result[1] = "删除失败,未选择账号!";
            return result;
        }
        String[] decryptIds = decryptIds(ids);
        int userid = InterfaceUtil.getAdminId();
        for(int i = 0; i < decryptIds.length; i++){
            if(ids[i].equals(String.valueOf(userid))){
                result[0] = false;
                result[1] = "删除失败,不能删除自己的账号!";
                return result;
            }
        }
        int userRoleCount = deleteUserRoleByUserID(decryptIds);
        int userCount = deleteUserByUserID("sys_user", "id", decryptIds);
        if(userCount != userRoleCount){
            result[0] = false;
            result[1] = "删除失败!";
            return result;
        }
        result[0] = true;
        result[1] = "删除成功!,删除记录数：" + userCount;
        return result;
    }

    /**
     * @Title: decryptedIds
     * @Description:TODO
     * @param ids
     * @throws Exception
     *             void
     */

    private String[] decryptIds(String[] ids){
        try{
            String[] decryptedIds = new String[ids.length];
            for(int i = 0; i < ids.length; i++){
                decryptedIds[i] = decryptId(ids[i]);
            }
            return decryptedIds;
        }
        catch(Exception e){
            e.printStackTrace();
            return new String[0];
        }
    }

    private int deleteUserByUserID(String tableName, String col, String[] ids){
        StringBuffer sb = new StringBuffer();
        sb.append("DELETE FROM sys_user WHERE id IN( ");
        for(int i = 0; i < ids.length; i++){
            if(i == ids.length - 1){
                sb.append("?");
            } else{
                sb.append("?,");
            }
        }
        sb.append(") ");
        int orgId = InterfaceUtil.getOrgId();
        String chlidOrgIdSql = InterfaceUtil.getChlidOrgIdSql(orgId, Constant.MAX_ORG_LEVEL, true);
        sb.append("AND org_id IN");
        sb.append(chlidOrgIdSql);
        logger.info("Delete user sql:" + sb.toString());
        return Db.update(sb.toString(), (Object[])ids);
    }

    private int deleteUserRoleByUserID(String[] ids){
        StringBuffer sb = new StringBuffer();
        sb.append("DELETE FROM sys_user_role WHERE  user_id in ( SELECT id FROM sys_user WHERE id IN (");
        for(int i = 0; i < ids.length; i++){
            if(i == ids.length - 1){
                sb.append("?");
            } else{
                sb.append("?,");
            }
        }
        sb.append(") ");
        int orgId = InterfaceUtil.getOrgId();
        String chlidOrgIdSql = InterfaceUtil.getChlidOrgIdSql(orgId, Constant.MAX_ORG_LEVEL, true);
        sb.append("AND org_id IN");
        sb.append(chlidOrgIdSql);
        sb.append(")");
        logger.info("Delete user sql:" + sb.toString());
        return Db.update(sb.toString(), (Object[])ids);
    }

    /**
     * @Title: getUserRoleType
     * @Description:根据用户ID查询用户所属角色类型
     * @param userId:用户id
     * @return int:用户所属角色类型(20普通管理原，50供应商管理员)
     */
    public int getUserRoleType(int userId){
        Record record = Db.findFirst(
                                     "SELECT type FROM sys_user su, sys_user_role sur, sys_role sr WHERE su.id=? and su.id=sur.user_id and sur.role_id = sr.id;",
                                     userId);
        return record.getInt("type");
    }

    public String decryptId(String id) throws Exception{
        return desas.decrypt(id);
    }
    public String encryptId(String id) throws Exception{
        return desas.encrypt(id);
    }

}
